import UIExtensionAbility from '@ohos.app.ability.UIExtensionAbility';
import Want from '@ohos.app.ability.Want';
import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession';
import Logger from '../adsmanager/log/HiAdLog';

const TAG: string = '[AdsUIExtensionAbility]';

/**
 * UEA入口
 */
export default class AdsUIExtensionAbility extends UIExtensionAbility {
  onCreate() {
    Logger.i(TAG, `AdsUIExtensionAbility test onCreate`);
    Logger.i(TAG, `AdsUIExtensionAbility test onCreate dir :${this.context.cacheDir}`);
  }

  onSessionCreate(want: Want, session: UIExtensionContentSession) {
    Logger.i(TAG, `AdsUIExtensionAbility test onSessionCreate`);
    const storage = new LocalStorage();
    storage.setOrCreate('session', session);
    let parameters = want?.parameters;
    Logger.i(TAG, `AdsUIExtensionAbility AdDisplayOptions: ${JSON.stringify(parameters)}`);
    let AdDisplayOptions = want?.parameters["displayOptions"];
    // 当AdDisplayOptions中存在refreshTime属性的时候，认为客户端请求自动刷新广告
    if (AdDisplayOptions["refreshTime"]) {
      // 当请求自动刷新广告的时候，拉起自动刷新广告展示页面
      Logger.i(TAG, `AdsUIExtensionAbility refreshTime: ${AdDisplayOptions["refreshTime"]}`);
      this.sessionDataCallback(session);
    } else {
      // 拉起广告组件广告展示页面
      session.loadContent("adsmanager/pages/UIExtensionAbilityPage", storage);
    }
  }

  /**
   * 设置UIExtensionAbility的回调以从UIExtensionComponent接收数据
   */
  sessionDataCallback(session: UIExtensionContentSession) {
    Logger.i(TAG, 'sessionDataCallback');
    // 发送给客户端onAdOpen事件
    session.sendData({
      status: 'onAdOpen', ad: {}, data: 'AdsTest'
    });

    session.setReceiveDataCallback((data) => {
      Logger.i(TAG, `setReceiveDataCallback:${(JSON.stringify(data))}`);
      session.loadContent("adsmanager/pages/AutoRefreshPage");
    })
  }
}
